package com.awenhui.demo.core.handler;

import java.util.List;
import java.util.stream.Collectors;

import com.awenhui.demo.core.base.ActionResult;
import com.awenhui.demo.core.base.BaseController;
import com.awenhui.demo.core.base.ResultCode;
import com.awenhui.demo.core.exception.ActionException;

import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局统一异常处理（无法处理过滤器中的异常）
 *
 * @author yuxf
 */
@RestControllerAdvice
public class GlobalExceptionHandler extends BaseController {

    /**
     * 处理所有不可知的异常
     * 
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public ActionResult<?> handleException(Exception e) {
        e.printStackTrace();
        ActionResult<Object> actionResult = new ActionResult<>();
        actionResult.setSuccess(false);
        actionResult.setCode(HttpStatus.BAD_REQUEST.value());
        actionResult.setMessage(e.getMessage()==null?e.toString():e.getMessage());
        return actionResult;
    }

    /**
     * ActionException处理
     * 
     * @return
     */
    @ExceptionHandler(ActionException.class)
    public ActionResult<?> actionException(ActionException e) {
        e.printStackTrace();
        return (ActionResult<?>) e.getResult();

    }

        /**
     * 处理请求参数校验(实体对象传参)异常
     *
     * @param e ${@link MethodArgumentNotValidException}
     * @return ActionResult ${@link ActionResult}
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ActionResult<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        e.printStackTrace();
        StringBuilder sb = new StringBuilder();
        List<ObjectError> errorList = e.getBindingResult().getAllErrors();

        for (ObjectError error : errorList) {
            
            sb.append(",").append(error.getDefaultMessage());
        }
        String errMeg = sb.toString().replaceFirst(",", "");
      
        return error(ResultCode.VERIFICATION_FAILED.getValue(), errMeg);
    }

    @ExceptionHandler(value = BindException.class)
    public ActionResult<?> handleBindException(BindException e) {
        e.printStackTrace();
        String message = e.getBindingResult().getAllErrors().stream().map(r->"error:"+r.getDefaultMessage()).collect(Collectors.joining(","));
        return error(ResultCode.VERIFICATION_FAILED.getValue(), message);
    }
}